package users

import (
	"go_auth/ext/e"
	"go_auth/ext/settings"
	"go_auth/utils/commons"
	"time"
)

type CertKey struct {
	Uid         string    `xorm:" varchar(100) 'uid'"`
	Key         string    `xorm:" varchar(100) 'key'"`
	CreateTime  time.Time `xorm:"created 'create_time'"`
	UpdatedTime time.Time `xorm:"updated 'update_time'" `
}

func CheckCertCode(uid string) (bool, string) {
	c := new(CertKey)
	_, err := settings.MasterDB.Where("uid = ? ", uid).Get(c)
	if !commons.CheckErr(err) {
		return false, ""
	}
	return true, c.Key

}

func AddCertCode(uid string) int {
	if ok, _ := CheckCertCode(uid); ok {
		return e.SourceExist
	}
	var secretId string
	c := new(CertKey)
	secretId = commons.RandNewStr(32)
	c.Key = secretId
	c.Uid = uid

	insert, err := settings.MasterDB.Insert(c)
	if commons.CheckErr(err) {
		return int(insert)
	}
	return e.Success
}

func UpdateCertCode(uid string) int {
	c := new(CertKey)
	secretId := commons.RandNewStr(32)
	c.Key = secretId
	affected, err := settings.MasterDB.Where("uid = ? ", uid).Update(c)
	if commons.CheckErr(err) {
		return int(affected)
	}
	return e.Success
}

func DeleteCertCode(uid string) int {
	c := new(CertKey)
	affected, err := settings.MasterDB.Where("uid = ? ", uid).Delete(c)
	if commons.CheckErr(err) {
		return int(affected)
	}
	return e.Success
}

/**
这里查看的时候关联用户表和角色表(显示用户名和角色)
*/

type CertCodeGroup struct {
	UserName   string
	Uid        string
	Staff      int
	Status     int
	Key        string
	UpdateTime string
}

func FindCertCode() (interface{}, int64) {
	var group []CertCodeGroup
	count, err := settings.MasterDB.Table("user").Alias("u").Select("u.user_name,u.uid,u.staff,u.status,ck.key,ck.update_time").
		Join("INNER", []string{"cert_key", "ck"}, "ur.uid=ck.uid").FindAndCount(&group)

	if !commons.CheckErr(err) {
		return nil, 0
	}
	return group, count
}
